#!/bin/bash

#Directory
TARGET_DIR="/usr/lib"
SOURCE_DIR="redistributables/bin"
INCLUDE_TARGET_DIR="/usr/include"
INCLUDE_SOURCE_DIR="redistributables/include"

#File
IOPORT="libStarIOPort"
IOJ="libStarIOJ"
LIBUSB="libstarusb"
INC_DIR="starmicronics"

#Version
MAJOR="2"
MINOR="9"
REVISION="0"
VERSION="${MAJOR}.${MINOR}.${REVISION}"

LIB_LIST=( "${IOPORT}.so" "${IOPORT}.so.${MAJOR}" "${IOPORT}.so.${VERSION}"   "${IOJ}.so" "${IOJ}.so.${MAJOR}" "${IOJ}.so.${VERSION}"  "${LIBUSB}.so" "${LIBUSB}.so.${MAJOR}" "${LIBUSB}.so.${VERSION}" )

HEADER_LIST=( "StarIOPort.h" "${INC_DIR}/Platform.h" "${INC_DIR}/platform/Linux.h" )

function checkAlreadyInstalled()
{
    for filename in ${LIB_LIST[@]}
    do
    if [ -e "${TARGET_DIR}/${filename}" ]
    then
        return 1
    fi
    done

    for filename in ${HEADER_LIST[@]}
    do
    if [ -e "${TARGET_INCLUDE_DIR}/${filename}" ]
    then
        return 1
    fi
    done

    return 0
}

checkAlreadyInstalled
if [ $? == 1 ]
then
    input="n"
    while [ $input != "y" ]
    do
    echo "StarIO is already installed. Overwrite it? [y/n]"
    read input
    if [ $input == "n" ]
    then
        exit 0
    fi
    done
fi

#Install library
cp -pf ${SOURCE_DIR}/${IOPORT}.so.${VERSION} ${TARGET_DIR}
cp -pf ${SOURCE_DIR}/${IOJ}.so.${VERSION} ${TARGET_DIR}
cp -pf ${SOURCE_DIR}/${LIBUSB}.so.${VERSION} ${TARGET_DIR}

#Install header file
chmod 755 ${INCLUDE_SOURCE_DIR}/${INC_DIR}
chmod 644 ${INCLUDE_SOURCE_DIR}/${INC_DIR}/Platform.h
chmod 644 ${INCLUDE_SOURCE_DIR}/${INC_DIR}/StarIOPort.h
chmod 755 ${INCLUDE_SOURCE_DIR}/${INC_DIR}/platform
chmod 644 ${INCLUDE_SOURCE_DIR}/${INC_DIR}/platform/Linux.h

cp -pfr ${INCLUDE_SOURCE_DIR}/* ${INCLUDE_TARGET_DIR}
ldconfig -n ${TARGET_DIR}
ln -fs ${TARGET_DIR}/${IOPORT}.so.${MAJOR} ${TARGET_DIR}/${IOPORT}.so
ln -fs ${TARGET_DIR}/${IOJ}.so.${MAJOR} ${TARGET_DIR}/${IOJ}.so
ln -fs ${TARGET_DIR}/${LIBUSB}.so.${MAJOR} ${TARGET_DIR}/${LIBUSB}.so

echo "Complete!"
